package Demo2_6;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User：Lenovo
 * Date:2025-02-06
 * Time:18:46
 */
// 定义二叉树节点类
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class SymmetricTree {
    // 主方法，用于检查二叉树是否轴对称
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        // 调用辅助方法，比较左子树和右子树
        return isMirror(root.left, root.right);
    }

    // 辅助方法，用于递归比较两棵树是否对称
    private boolean isMirror(TreeNode t1, TreeNode t2) {
        // 如果两棵树都为空，说明对称
        if (t1 == null && t2 == null) {
            return true;
        }
        // 如果其中一棵树为空，另一棵不为空，说明不对称
        if (t1 == null || t2 == null) {
            return false;
        }
        // 比较当前节点的值，以及左子树的左节点和右子树的右节点、左子树的右节点和右子树的左节点
        return (t1.val == t2.val) && isMirror(t1.left, t2.right) && isMirror(t1.right, t2.left);
    }

    public static void main(String[] args) {
        // 构建一个示例二叉树
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(2);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(4);
        root.right.left = new TreeNode(4);
        root.right.right = new TreeNode(3);

        SymmetricTree solution = new SymmetricTree();
        // 调用 isSymmetric 方法检查二叉树是否轴对称
        boolean result = solution.isSymmetric(root);
        System.out.println("该二叉树是否轴对称: " + result);
    }
}
